<template>
  <div>
    <ul class="tab">
      <li
        v-for="(item, i) in tabs"
        :key="i"
        @click="change(item)"
        :class="item == showType ? 'active' : ''"
      >
        {{ item }}
      </li>
    </ul>
    <div class="btn">
      <span @click="Sort($event)">升序(按新闻类型数量)</span>
      <span @click="Sort($event)">降序(按新闻类型数量)</span>
    </div>
    <div class="news">
      <li v-for="(ele, index) in newsList" :key="index">
        <a :href="ele.href">{{ ele.title }}</a>
      </li>
    </div>
  </div>
</template>
<script>
let json = [
  {
    title: "出现跑路，北京全面排查P2P风险",
    type: "互联网",
    href: "http://tech.163.com/14/0610/08/9UC5IJQE000915BF.html",
  },
  {
    title: "北京傍晚到夜间有雷阵雨 明天白天多云转晴",
    type: "国内",
    href: "http://news.hexun.com/2014-06-10/165566949.html",
  },
  {
    title: "“10亿美元俱乐部”的宠儿有哪些？",
    type: "互联网",
    href: "http://www.pingwest.com/2014-startups-with-billion-dollar-valuations/",
  },
  {
    title: "恒大官方宣布于汉超李学鹏加盟 制海报欢迎(图)",
    type: "体育",
    href: "http://sports.sina.com.cn/j/2014-06-10/19177202125.shtml",
  },
  {
    title: "外交部称美国是“黑客帝国”：地球人都知道",
    type: "互联网",
    href: "http://politics.caijing.com.cn/2014-06-10/114251776.html",
  },
  {
    title: "乌克兰卢甘斯克机场被关闭",
    type: "军事",
    href: "http://stock.sohu.com/20140610/n400627314.shtml",
  },
];
export default {
  data() {
    return {
      tabs: ["全部", "互联网", "国内", "体育", "军事"],
      newsList: json,
      showType: "全部",
      sortType: "",
    };
  },
  methods: {
    change(item) {
      this.showType = item;
      if (item == "全部") {
        this.newsList = json;
      } else {
        this.newsList = json.filter((ele) => {
          return ele.type.includes(this.showType);
        });
      }
    },
    Sort(e) {
      let num = {};
      for (const item of json) {
        const { type } = item;
        if (num[type]) {
          num[type]++;
        } else {
          num[type] = 1;
        }
      }
      this.newsList.forEach((item) => {
        for (const i in num) {
          if (item.type == i) {
            this.$set(item, "num", num[i]);
          }
        }
      });
      if (e.target.innerHTML.includes('升序')) {
        this.newsList.sort((a, b) => {
          return a.num - b.num;
        });
      }
      if (e.target.innerHTML.includes('降序')) {
        this.newsList.sort((a, b) => {
          return b.num - a.num;
        });
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.tab {
  display: flex;

  li {
    list-style: none;
    width: 100px;
    height: 50px;
    border: 1px solid red;
    text-align: center;
    line-height: 50px;
    margin: 20px;
  }
  .active {
    background-color: #d00;
  }
}
.btn {
  span {
    margin: 10px;
    color: #7b1a8b;
  }
}
</style>